<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
    <BasicForm @register="registerForm" name="BizChargeStationForm">
      <template #operatorIdSlot1="{ model, field }">
        <a-select ref="select" v-model:value="model[field]">
          <a-select-option v-for="item in operatorIdList" :value="item.value">{{ item.label
            }}</a-select-option>
        </a-select>
      </template>
      <template #dituxuandian="{ model, field }">
        <a @click="openMap">
          <a-icon type="environment" />点击选择经纬度
        </a>
      </template>

    </BasicForm>
  </BasicModal>
  <a-modal :zIndex="99999" style="z-index: 99999;" width='1000px' v-model:open="visibleMap" title="点击选择经纬度" @ok="visibleMap = false">
    <a-card style="width: 1000px">
      <p>纬度 lat:{{ mapDate.lat }}</p>
      <p>经度 lng:{{ mapDate.lng }}</p>
      <!-- <a-spin :spinning="spinning"> -->
      <div ref="wrapRef2" style="width:100%;height:500px;"></div>
      <!-- </a-spin> -->
    </a-card>

  </a-modal>
</template>

<script lang="ts" setup>
import {ref, computed, unref, onMounted} from 'vue';
import {BasicModal, useModalInner} from '/@/components/Modal';
import {BasicForm, useForm} from '/@/components/Form/index';
import {formSchema} from '../BizChargeStation.data';
import {saveOrUpdate} from '../BizChargeStation.api';
// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const isDetail = ref(false);
//表单配置
const [registerForm, {setProps, resetFields, setFieldsValue, validate, scrollToField, removeSchemaByFiled, getFieldsValue}] = useForm({
	//labelWidth: 150,
	schemas: formSchema,
	showActionButtonGroup: false,
	baseColProps: {span: 24},
});
// 地图
import {useScript} from '/@/hooks/web/useScript';
// const A_MAP_URL = 'https://webapi.amap.com/maps?v=2.0&key=dc81674b231824b7c4ca9dd8c72a9b4f';
const A_MAP_URL = 'https://webapi.amap.com/maps?v=2.0&key=35b11c90308c1e231bdfff268f9d0bfd';
const wrapRef2 = ref<HTMLDivElement | null>(null);
const {toPromise} = useScript({src: A_MAP_URL});
const visibleMap = ref(false);
const spinning = ref(true);
var map;
const mapDate = ref({lat: 0, lng: 0});
async function mapInit() {
	await toPromise();
	await nextTick();
	const wrapEl = unref(wrapRef2);
	if (!wrapEl) return;
	const AMap = (window as any).AMap;
	map = new AMap.Map(wrapEl, {
		resizeEnable: true,
		center: [117.220482, 39.101554], // [120.583545, -1.55236], //101.707353,3.152778  ///117.2, 39.13
		zoom: 9,
		mapStyle: 'amap://styles/a7522026b0cdac16f340562a80203536',
		lang: 'zh_cn', //可选值：en，zh_en, zh_cn
	});
	spinning.value = false;

	map.on('click', function (e) {
		mapDate.value.lat = e.lnglat.lat;
		mapDate.value.lng = e.lnglat.lng;
		setFieldsValue({stationLng: mapDate.value.lng, stationLat: mapDate.value.lat});
		// lnglatInput.value = e.lnglat.toString()
	});
}
function openMap() {
	visibleMap.value = true;
	setTimeout(() => {
		// this.$nextTick(() => {
		mapInit();
		// })
	}, 1000);
}

//表单赋值
const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
	//重置表单
	await resetFields();
	setModalProps({confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter});
	isUpdate.value = !!data?.isUpdate;
	isDetail.value = !!data?.showFooter;
	if (unref(isUpdate)) {
		//表单赋值
		await setFieldsValue({
			...data.record,
		});
	}
	// console.log('!unref(isDetail)', isDetail.value);
	// 不同状态隐藏条件
	if (isDetail.value) {
		removeSchemaByFiled(['dcChargers', 'acChargers', 'totalPower']);
	}
	// 隐藏底部时禁用整个表单
	setProps({disabled: !data?.showFooter});
});
// 所属运营商下拉框数据
const operatorIdList = ref([]);
onMounted(async () => {
	//获取下拉框数据
	operatorIdList.value = JSON.parse(window.localStorage.getItem('operatorIdList'));
	console.log('获取下拉框数据', operatorIdList);
});

//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增' : !unref(isDetail) ? '详情' : '编辑'));
//表单提交事件
async function handleSubmit(v) {
	console.log('v', v, getFieldsValue());
	try {
		let values = await validate();
		setModalProps({confirmLoading: true});
		//提交表单
		await saveOrUpdate(values, isUpdate.value);
		//关闭弹窗
		closeModal();
		//刷新列表
		emit('success');
	} catch ({errorFields}) {
		if (errorFields) {
			const firstField = errorFields[0];
			if (firstField) {
				scrollToField(firstField.name, {behavior: 'smooth', block: 'center'});
			}
		}
		return Promise.reject(errorFields);
	} finally {
		setModalProps({confirmLoading: false});
	}
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
	width: 100%;
}

:deep(.ant-calendar-picker) {
	width: 100%;
}
</style>
